﻿using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using XFControls.XFPanels;
using XFControls.XFPanels.XFPanelItems;
using FBEntities;
using FBEntities.FBObjects;
using XFItemControls.XFPanels.XFPanelItems;

namespace XDAFacebook
{
    public partial class Friends : Form
    {
        public Friends()
        {
            InitializeComponent();
            XFPanelList panel = new XFPanelList();
            var loading = new XFItemLoading(new XFWorkerLoadFriends(new FBEntities.FBObjects.User.FBPerson()));
            panel.Add(loading);
            panel.ScrollbarColor = Color.LightSlateGray;

            xfPanelMain.SetHeader(xfPanelHeader);
            xfPanelMain.SetMainPanel(panel);
            FBDataSource ds = new FBDataSource("False");
            AddFriends(ds);
        }

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        public void AddFriends(FBDataSource ds)
        {
            XFPanelList panel = new XFPanelList();
            if (ds.Me.Friends.data.Count == 0)
            {
                var empty = new XFItemSimpleText("You have no friends :'(");
                panel.Add(empty);
                panel.ScrollbarColor = Color.LightSlateGray;

                xfPanelMain.SetMainPanel(panel);
                return;
            }


            var friends = ds.Me.Friends.data;
            friends.Sort(new Comparison<FBProxyPerson>(FriendCompare));
            char[] curLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".ToCharArray();
            int cur = 0;
            panel.Add(curLetter[cur].ToString());

            foreach (var friend in friends)
            {
                string fLast = friend.name.Split(' ').Last();

                if (!fLast.StartsWith(curLetter[cur].ToString()))
                {
                    int tempCur = Array.IndexOf(curLetter, fLast[0]);
                    if (tempCur > 0)
                    {
                        cur = tempCur;
                        panel.Add(curLetter[cur].ToString());
                    }
                }

                var f = new XFItemFriend();
                f.Name = friend.name;
                panel.Add(f);
            }

            xfPanelMain.SetMainPanel(panel);
            xfPanelMain.ShowAlphaBar(true);
            xfPanelMain.ShowScrollbar(true);

            return;
        }

        private int FriendCompare(FBProxyPerson f1, FBProxyPerson f2)
        {
            string f1Last = f1.name.Split(' ').Last();
            string f2Last = f2.name.Split(' ').Last();

            return f1Last.CompareTo(f2Last);
        }
    }
}